import datetime

from flask import Blueprint, request, send_file, jsonify
from app.BaseApp import app
from flask import Flask, render_template, request, send_file, redirect, url_for
import os
import barcode
from barcode.writer import ImageWriter
from PIL import Image
import io
import uuid
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4
from reportlab.lib.units import cm

generate_barcodes = Blueprint("generate_barcodes", __name__, static_folder="static", url_prefix='/generate_barcodes')

app.config['UPLOAD_FOLDER'] = 'app/Blueprint/GenerateBarcodes/static/barcodes'
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024  # 16MB

# # 确保目录存在
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)


def generate_barcode(number, width_cm=14, height_cm=2):
    """生成指定大小的条码图片"""
    # 转换为像素 (1cm = 37.8px)
    width_px = int(width_cm * 37.8)
    height_px = int(height_cm * 37.8)

    # 生成Code128条码
    code128 = barcode.get_barcode_class('code128')
    barcode_img = code128(number, writer=ImageWriter())

    # 保存为临时文件
    filename = f"{uuid.uuid4()}.png"
    filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
    barcode_img.save(filepath, options={'write_text': False})

    # 调整图片大小
    img = Image.open(filepath+".png")
    img = img.resize((width_px, height_px), Image.LANCZOS)
    img.save(filepath)

    return filename


@generate_barcodes.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        # 获取表单数据
        inspection_type = request.form.get('inspection_type', '经营性棉花公证检验')
        batch_number = request.form.get('batch_number', '123')
        sample_number = request.form.get('sample_number', '345')
        origin = request.form.get('origin', '河南郑州')
        package_number = request.form.get('package_number', '332')
        sampling_date = request.form.get('sampling_date', '20250918')
        start_number = request.form.get('start_number', '000000000000000001')
        barcode_count = int(request.form.get('barcode_count', 10))
        width_cm = float(request.form.get('width_cm', 14))
        height_cm = float(request.form.get('height_cm', 2))
        remark = request.form.get('remark', '河南郑州')

        # 生成条码序列
        barcode_numbers = []
        for i in range(barcode_count):
            num = int(start_number) + i
            barcode_numbers.append(f"{num:018d}")

        # 生成条码图片
        barcode_images = []
        for number in barcode_numbers:
            filename = generate_barcode(number, width_cm, height_cm)
            barcode_images.append({
                'number': number,
                'filename': filename
            })

        # 保存参数用于打印页面
        print_data = {
            'inspection_type': inspection_type,
            'batch_number': batch_number,
            'sample_number': sample_number,
            'origin': origin,
            'package_number': package_number,
            'sampling_date': sampling_date,
            'barcode_images': barcode_images,
            'width_cm': width_cm,
            'height_cm': height_cm,
            'now': datetime.datetime.now(),
            'remark': remark
        }

        return render_template('print.html', **print_data)

    return render_template('index.html')


@app.route('/print-pdf', methods=['POST'])
def print_pdf():
    # 获取打印数据
    data = request.json
    barcode_images = data['barcode_images']
    width_cm = float(data['width_cm'])
    height_cm = float(data['height_cm'])

    # 创建PDF
    buffer = io.BytesIO()
    c = canvas.Canvas(buffer, pagesize=A4)
    width, height = A4

    # 设置页边距
    margin = 1 * cm
    x_start = margin
    y_start = height - margin - (height_cm * cm)

    # 每行条码数量
    barcodes_per_row = 2

    # 添加条码到PDF
    for i, barcode in enumerate(barcode_images):
        row = i // barcodes_per_row
        col = i % barcodes_per_row

        x = x_start + col * (width_cm * cm + 1 * cm)
        y = y_start - row * (height_cm * cm + 1 * cm)

        # 检查是否需要新页面
        if y < margin:
            c.showPage()
            y = height - margin - (height_cm * cm)
            row = 0
            col = i % barcodes_per_row
            x = x_start + col * (width_cm * cm + 1 * cm)

        # 添加条码图片
        img_path = os.path.join('static/barcodes', barcode['filename'])
        c.drawImage(img_path, x, y, width_cm * cm, height_cm * cm)

        # 添加条码编号
        text_y = y - 0.5 * cm
        c.setFont("Helvetica", 9)
        c.drawString(x, text_y, barcode['number'])

    c.save()

    buffer.seek(0)
    return send_file(
        buffer,
        as_attachment=True,
        download_name='barcodes.pdf',
        mimetype='application/pdf'
    )

